﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EngineOfEvermore.Scene;
using EngineOfEvermore.Scene.Input;
using GorgonLibrary.InputDevices;
using EngineOfEvermore.Common;
using EngineOfEvermore.Scene.Visual;

namespace EngineOfEvermore.GameApp
{
    enum CharacterModelCommand
    { 
        MSG_MOVE_UP_BEGIN,
        MSG_MOVE_DOWN_BEGIN,
        MSG_MOVE_LEFT_BEGIN,
        MSG_MOVE_RIGHT_BEGIN,

        MSG_MOVE_UP_END,
        MSG_MOVE_DOWN_END,
        MSG_MOVE_LEFT_END,
        MSG_MOVE_RIGHT_END
    }

    class TestCharacterModel : SceneObjectComponent
    {
        class InternalUpdateTask : Task
        {
            TestCharacterModel _owner;

            public InternalUpdateTask( TestCharacterModel owner ):
                base( 100 )
            {
                _owner = owner;
            }

            public override void Execute( LogicUpdateEventArgs e )
            {
                _owner._update();
            }
        }

        Queue<CharacterModelCommand> _commandQueue = new Queue<CharacterModelCommand>();
        InternalUpdateTask _updateTask;
        VisualComponent _visualComponent;
        bool[] _keyStates = new bool[4];
        int _lookingDirection = RIGHT;

        const int RIGHT = 0;
        const int LEFT = 1;
        const int UP = 2;
        const int DOWN = 3;

        const float WALK_SPEED = 220.0f;

        public TestCharacterModel()
        {
            _updateTask = new InternalUpdateTask( this );
        }

        public void ReceiveCommand( CharacterModelCommand c )
        {
            _commandQueue.Enqueue( c );
        }

        protected override void OnAddToScene( SceneGraph scene )
        {
            base.OnAddToScene( scene );

            scene.TimeContext.AddRepeatingTask( _updateTask );
        }

        protected override void OnRemoveFromScene( SceneGraph scene )
        {
            scene.TimeContext.RemoveRepeatingTask( _updateTask );

            base.OnRemoveFromScene( scene );
        }

        protected override void OnSiblingAdded( SceneObjectComponent sibling )
        {
            if ( sibling is VisualComponent )
            {
                _visualComponent = (VisualComponent) sibling;
            }
        }

        protected override void OnSiblingRemoved( SceneObjectComponent sibling )
        {
            if ( sibling is VisualComponent )
            {
                _visualComponent = null;
            }
        }

        void _update()
        {
            while ( _commandQueue.Count != 0 )
            {
                var command = _commandQueue.Dequeue();
                _processCommand( command );
            }
        }

        void _processCommand( CharacterModelCommand command )
        {
            switch ( command )
            {
                case CharacterModelCommand.MSG_MOVE_DOWN_BEGIN:
                    if ( _keyStates[DOWN] )
                        return;

                    _keyStates[DOWN] = true;
                    break;

                case CharacterModelCommand.MSG_MOVE_DOWN_END:
                    _keyStates[DOWN] = false;
                    break;

                case CharacterModelCommand.MSG_MOVE_UP_BEGIN:
                    if ( _keyStates[UP] )
                        return;

                    _keyStates[UP] = true;
                    break;

                case CharacterModelCommand.MSG_MOVE_UP_END:
                    _keyStates[UP] = false;
                    break;

                case CharacterModelCommand.MSG_MOVE_LEFT_BEGIN:
                    if ( _keyStates[LEFT] )
                        return;

                    _keyStates[LEFT] = true;
                    break;

                case CharacterModelCommand.MSG_MOVE_LEFT_END:
                    _keyStates[LEFT] = false;
                    break;

                case CharacterModelCommand.MSG_MOVE_RIGHT_BEGIN:
                    if ( _keyStates[RIGHT] )
                        return;

                    _keyStates[RIGHT] = true;
                    break;

                case CharacterModelCommand.MSG_MOVE_RIGHT_END:
                    _keyStates[RIGHT] = false;
                    break;
            }

            Vector2d walkingDirection = new Vector2d( 0, 0 );

            if ( _keyStates[LEFT] )
            {
                walkingDirection.X -= 1;
            }

            if ( _keyStates[RIGHT] )
            {
                walkingDirection.X += 1;
            }

            if ( _keyStates[UP] )
            {
                walkingDirection.Y -= 1;
            }

            if ( _keyStates[DOWN] )
            {
                walkingDirection.Y += 1;
            }

            walkingDirection.Normalize();
            walkingDirection.Y *= 0.75f;

            AnimatedSprite mainSprite = (AnimatedSprite) _visualComponent.Children["main"];

            if ( walkingDirection.Length.EpsilonIsZero() )
            {
                Owner.LinearVelocity = new Vector2d();

                switch ( _lookingDirection )
                {
                    case RIGHT:
                        mainSprite.CurrentAnimation = "IdleRight";
                        mainSprite.FlipX = false;
                        break;

                    case LEFT:
                        mainSprite.CurrentAnimation = "IdleRight";
                        mainSprite.FlipX = true;
                        break;

                    case UP:
                        mainSprite.CurrentAnimation = "IdleUp";
                        mainSprite.FlipX = false;
                        break;

                    case DOWN:
                        mainSprite.CurrentAnimation = "IdleDown";
                        mainSprite.FlipX = false;
                        break;
                }
            }
            else
            {
                Owner.LinearVelocity = walkingDirection * WALK_SPEED;

                if ( !walkingDirection.X.EpsilonIsZero() )
                {
                    if ( walkingDirection.X < 0.0f )
                    {
                        _lookingDirection = LEFT;
                        mainSprite.CurrentAnimation = "WalkRight";
                        mainSprite.FlipX = true;
                    }
                    else
                    {
                        _lookingDirection = RIGHT;
                        mainSprite.CurrentAnimation = "WalkRight";
                        mainSprite.FlipX = false;
                    }
                }
                else
                {
                    if ( walkingDirection.Y < 0.0f )
                    {
                        _lookingDirection = UP;
                        mainSprite.CurrentAnimation = "WalkUp";
                        mainSprite.FlipX = false;
                    }
                    else 
                    {
                        _lookingDirection = DOWN;
                        mainSprite.CurrentAnimation = "WalkDown";
                        mainSprite.FlipX = false;
                    }
                }
            
            }

        }

    }

    class TestCharacterController : SceneObjectComponent
    {
        TestCharacterModel _model;

        protected override void OnAddToScene( SceneGraph scene )
        {
            base.OnAddToScene( scene );

            InputSubSystem iss = scene.GetSubSystem<InputSubSystem>();

            iss.KeyPressed += _onKeyPressed;
            iss.KeyReleased += _onKeyReleased;
        }

        protected override void OnRemoveFromScene( SceneGraph scene )
        {
            InputSubSystem iss = scene.GetSubSystem<InputSubSystem>();

            iss.KeyPressed -= _onKeyPressed;
            iss.KeyReleased -= _onKeyReleased;

            base.OnRemoveFromScene( scene );
        }

        protected override void OnSiblingAdded( SceneObjectComponent sibling )
        {
            base.OnSiblingAdded( sibling );

            if ( sibling is TestCharacterModel )
            {
                _model = (TestCharacterModel) sibling;
            }
        }

        protected override void OnSiblingRemoved( SceneObjectComponent sibling )
        {
            if ( sibling is TestCharacterModel )
            {
                sibling = null;
            }

            base.OnSiblingRemoved( sibling );
        }

        void _onKeyPressed( object sender, KeyboardInputEventArgs e )
        {
            if ( _model != null )
            {
                switch ( e.Key )
                { 
                    case KeyboardKeys.Left:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_LEFT_BEGIN );
                        break;

                    case KeyboardKeys.Right:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_RIGHT_BEGIN );
                        break;

                    case KeyboardKeys.Up:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_UP_BEGIN );
                        break;

                    case KeyboardKeys.Down:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_DOWN_BEGIN );
                        break;
                }
            }
        }

        void _onKeyReleased( object sender, KeyboardInputEventArgs e )
        {
            if ( _model != null )
            {
                switch ( e.Key )
                {
                    case KeyboardKeys.Left:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_LEFT_END );
                        break;

                    case KeyboardKeys.Right:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_RIGHT_END );
                        break;

                    case KeyboardKeys.Up:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_UP_END );
                        break;

                    case KeyboardKeys.Down:
                        _model.ReceiveCommand( CharacterModelCommand.MSG_MOVE_DOWN_END );
                        break;
                }
            }
        }

    }
}
